package blackWorlds

import (
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/blackWorlds/goswd"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/redis/cache"
	"time"
)

var BlackWorInstance BlackWordsInterface

type BlackWordsInterface interface {
	UpdateWords(keyWords []string) error
	ReplaceWithAsterisk(text string) string
}

func NewBlackWorlds() (BlackWordsInterface, error) {
	keyWords := getBlackKeyword()
	switch global.Config.GetString("filterLib") {
	case "dfa":
		//filter.InitWord(keyWords)
	default:
		return goswd.InitGoSwdWords(keyWords)
	}
	return goswd.InitGoSwdWords(keyWords)
}

func getBlackKeyword() []string {
	keyWords, err := db_main.GetBlackKeyword()
	if err != nil {
		global.Log.Errorf("获取黑名单词库出错: %v", err)
	}
	return keyWords
}

func LoopKeyWords() {
	// 初始化黑词过滤库
	var err error
	BlackWorInstance, err = NewBlackWorlds()
	if err != nil {
		panic(err)
	}
	go func() {
		timer := time.NewTicker(30 * time.Second)
		defer timer.Stop() // 在函数结束时停止定时器
		for {
			select {
			case <-timer.C:
				if cache.KeywordsCheckUpdate() {
					err := BlackWorInstance.UpdateWords(getBlackKeyword())
					if err != nil {
						global.Log.Errorf("更新关键词库失败: %v", err)
					} else {
						global.Log.Infof("黑词库更新成功")
						cache.DelKeywordsUpdate()
					}
				}
			}
		}
	}()
}
